//
//  PersonModel.swift
//  PerfectTemplatePackageDescription
//
//  Created by John on 2018/6/6.
//

import Foundation
import StORM
import MySQLStORM
import PerfectHTTP

class PersonModel: MySQLStORM {
    
    // ⚠️注意⚠️：第一个属性将成为主索引字段，所以应该是ID。
    var id              : Int = 0
    var firstname       : String? = ""
    var lastname        : String? = ""
    var email           : String? = ""
    var userName           : String? = ""
    var password           : String? = ""

    
    override open func table() -> String {
        return "persontable"
    }
    
    override func to(_ this: StORMRow) {
        if this.data["id"] is Int {
            
            id = this.data["id"] as! Int;
            
        }
            
        else if this.data["id"] != nil {
            
            let id32 = this.data["id"] as! Int32;
            
            id = Int(id32);
            
        }//这里有个坑，StORM在转化的时候id会返回Int32类型，但很多方法使用的时候都只能转成Int类型，所以这里处理成转换为Int类型，若有更好的方法可提出来
        firstname       = this.data["firstname"] as? String
        lastname        = this.data["lastname"] as? String
        email           = this.data["email"] as? String
        userName        = this.data["userName"] as? String
        password        = this.data["password"] as? String
    }
    
    func rows() -> [PersonModel] {
        var rows = [PersonModel]()
        for i in 0..<self.results.rows.count {
            let row = PersonModel()
            row.to(self.results.rows[i])
            rows.append(row)
        }
        return rows
    }
}

class NetRequest {
    
    
}

class UserRegister: NetRequest {
    
    
    
    public static func requestHandler(request: HTTPRequest, response: HTTPResponse) {
        
        // need to make sure something is available.
        
        let userName :String! = request.param(name: "userName");
        
        let password :String! = request.param(name: "password");
        
        let user = PersonModel();
        
        user.userName=userName;
        
        user.password=password;
        
//        let registerTime : String = try! formatDate(getNow(), format: "%Y-%m-%d %H:%M:%S”);//这里有个方法可以处理时间，swift Perfect 对foundation框架有很多坑，这里都是用Darwin和SwiftGlibc
//
//            user.registerTime = registerTime;
        
            try? user.find([("userName", userName)]);
        
            guard user.results.foundSetCount <= 0 else {
            
            //判断说明 该用户已存在
            
            response.sendData(data: ["code":100,"message":"用户名已存在"]);
            
            return;
            
            }
        
            try? user.save(set: { (id) in
            
                user.id=id as! Int//存储user数据到数据库里，并返回主键id，这里就有坑，若是id设置成int32类型，这里将不在走
            
            })
        
            guard user.results.insertedID > 0  else {
            
            //判断说明 注册是否成功（数据是否被插入数据库）
            
            response.sendData(data: ["code":100,"message":"注册失败"]);
            
            return;
            
            }
            
            response.sendData(data: ["code":200,"message":"注册成功","data":user.asDataDict()]);
        
    }
    
}
extension HTTPResponse {
    
    func sendData(data : [String:Any]) -> Void {
        
        var encodedString : String! = "";
        
        do {
            
            encodedString = try data.jsonEncodedString();
            
        }
            
        catch{
            
        }
        
        self.appendBody(string: encodedString);
        
        self.completed();
        
    }
    
}
